<template>
  <n-drawer v-model:show="modelValue.show" :width="600" :height="600" :placement="'bottom'">
    <n-drawer-content :title="toADDFlag ? '添加' : '修改'" closable :mask-closable="false">
      <n-form ref="formRef" :model="formValue" :rules="rules" :size="'medium'" label-placement="left" label-width="auto"
        require-mark-placement="right-hanging" :disabled="!modelValue.edit">
        <n-grid :cols="2" x-gap="20" y-gap="10">
          <n-form-item-gi label="id" path="id">
            <n-text>
              {{ formValue.id }} - {{ obj2Map(useConsts.getConsts().taskTypeMap).get(JSON.stringify(formValue.type)) }}
            </n-text>
          </n-form-item-gi>
          <n-form-item-gi label="名字" path="name">
            <n-input v-model:value="formValue.name" placeholder="输入名字" />
          </n-form-item-gi>
          <n-form-item-gi label="领域阶段" path="field">
            <n-tree-select v-model:value="formValue.fieldId" @update:value="
              formValue.stageId = null;
            getStageSelectFromBack(formValue.fieldId)
              " :options="fieldSelect" filterable
              :disabled="!toADDFlag || !props.modelValue.taskPanel || !modelValue.edit" />
            <n-select v-model:value="formValue.stageId" :options="stageSelect" filterable
              :disabled="!toADDFlag || !props.modelValue.taskPanel || !modelValue.edit" />
          </n-form-item-gi>
          <n-form-item-gi label="目标阶段" path="goal">
            <n-select v-model:value="formValue.goalId" :options="goalSelect" filterable disabled />
          </n-form-item-gi>
          <n-form-item-gi label="描述" path="desc">
            <n-input v-model:value="formValue.desc" type="textarea" placeholder="输入描述" rows="5" />
          </n-form-item-gi>
          <n-form-item-gi label="在截止日期前多久提醒" path="beforeDDL2Mention">
            <n-input-number v-model:value="formValue.timeMentionModal.beforeDDL2Mention" />
            <n-text type="error">提醒时间:
              <MyTime :time="TimeMentionModal.computeMentionTime(formValue.timeMentionModal, formValue.type)"></MyTime>
            </n-text>
          </n-form-item-gi>
          <n-form-item-gi label="在截止日期前多久提醒的单位" path="beforeDDL2MentionUnit">
            <n-select v-model:value="formValue.timeMentionModal.beforeDDL2MentionUnit" :options="dayUnitOptions" />
          </n-form-item-gi>
          <template v-if="formValue.type === 1">
            <n-form-item-gi label="截止日期" path="deadLine">
              <MyDatePicker v-model:time="formValue.timeMentionModal.deadLine"></MyDatePicker>
            </n-form-item-gi>
          </template>
          <template v-if="formValue.type === 2">
            <n-form-item-gi label="上次打卡时间" path="beginMentionTime">
              <MyDatePicker v-model:time="formValue.timeMentionModal.beginMentionTime"></MyDatePicker>
              <!--              <n-time :time="formValue.timeMentionModal.deadLine"></n-time>-->
            </n-form-item-gi>
            <n-form-item-gi label="下次打卡时间" path="newTime">
              <n-text type="error">
                <MyTime :time="TimeMentionModal.computeNextClockTime(formValue.timeMentionModal, formValue.type)">
                </MyTime>
              </n-text>
            </n-form-item-gi>
            <n-form-item-gi label="打卡周期" path="mentionPeriod">
              <n-input-number v-model:value="formValue.timeMentionModal.mentionPeriod" />
            </n-form-item-gi>
            <n-form-item-gi label="打卡周期单位" path="mentionUnit">
              <n-select v-model:value="formValue.timeMentionModal.mentionUnit" :options="dayUnitOptions" />
            </n-form-item-gi>
          </template>
          <n-form-item-gi label="状态" path="state">
            <n-select v-model:value="formValue.state" :options="stateOptions" :disabled="!toADDFlag" />
          </n-form-item-gi>
          <n-form-item-gi><n-button type="primary" @click="handleValidateClick" :disabled="!modelValue.edit">
              {{ toADDFlag ? "添加" : "修改" }}
            </n-button>
          </n-form-item-gi>
        </n-grid>

      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst, useMessage } from "naive-ui";
import { ref, computed, watch, Ref } from "vue";
import { UseConstsStore } from "@/store/modules/consts";
import { TimeMentionModal, TaskData, TaskMoreData, StageData } from "@/views/model/model";
import { timestampToDateTime } from "@/utils";
import { post, Response } from "@/api/http";
import { addStage, addTask, getFieldSelect, getGoalSelect, getStageSelect } from "@/api/url";
import useUserStore from "@/store/modules/user";
import MyTime from "@/views/task/time/MyTime.vue";
import { obj2Map } from "@/utils";
import MyDatePicker from "@/views/task/time/MyDatePicker.vue";

// 全局数据
const useSurfaceSetting = UseSurfaceSettingStore()
const useConsts = UseConstsStore()
const message = useMessage();
const userStore = useUserStore()

// 父组件数据
const props = defineProps<{
  modelValue: {
    show: boolean
    taskPanel: boolean
    edit: boolean
    key: number
    data: TaskMoreData
  }
  [key: string]: any
}>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return "undefined" == typeof modelValue.value.data.id || modelValue.value.data.id == null;
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
};
const formRef = ref<FormInst | null>(null);
const formValue = ref(modelValue.value.data);
watch(modelValue.value, async () => {
  formValue.value = modelValue.value.data
  await getGoalAndFieldSelect()
  // console.log(formValue.value)
});
const goalSelect = ref<Array<any>>([]);
const fieldSelect = ref<Array<any>>([]);
const stageSelect = ref<Array<any>>([]);
const getStageSelectFromBack = async (id: number | null) => {
  if (id) {
    console.log(id)
    try {
      const data: Response = await post({
        url: getStageSelect,
        data: { id: id },
        token: userStore.getToken()
      });
      // console.log(data)
      stageSelect.value = data.data.data
      // stageSelect.push(...)
      console.log(stageSelect)
    } catch (e) {
      message.error((e as Error).message)
    } finally {
    }
  }
}
const getGoalAndFieldSelect = async () => {
  try {
    const data: Response = await post({
      url: getGoalSelect,
      data: { haveFinish: false },
      token: userStore.getToken()
    });
    // console.log(data)
    goalSelect.value = data.data.data
    // console.log(goalSelect)
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
  try {
    const data: Response = await post({
      url: getFieldSelect,
      token: userStore.getToken()
    });
    // console.log(data)
    fieldSelect.value = data.data.data
    // console.log(fieldSelect)
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
  getStageSelectFromBack(formValue.value.fieldId)
}
const stateOptions = useConsts.getStateList().map(d => {
  return {
    label: d.label,
    value: parseInt(d.key)
  }
});
const dayUnitOptions = useConsts.getDayUnitMap().map(d => {
  return {
    label: d.label,
    value: parseInt(d.value)
  }
});
// 添加逻辑
const addItem = async (params: any) => {
  try {
    const data: Response = await post({
      url: addTask,
      data: params,
      token: userStore.getToken()
    });
    // console.log(data)
    message.success(data.msg)
    modelValue.value.show = false
    modelValue.value.key = Date.now()
  } catch (e) {
    message.error((e as Error).message)
  } finally {
  }
}
const addNew = () => {
  // const tosave = formValue.value;
  // if (
  //     formValue.value.timeMentionModal.deadLine !== null &&
  //     formValue.value.timeMentionModal.deadLine > 0 &&
  //     !(TimeMentionModal.computeMentionTime(formValue.value.timeMentionModal, formValue.value.type) > 0)
  // ) {
  //   message.error("请选择提醒时间");
  //   return;
  // }
  // if (tosave !== undefined) {
  //   const showStage = modelValue.value.stageId; // surfaceSetting.getShowStage();
  //   const satgeData = stageList.getStageDataById(showStage);
  //   if (satgeData !== undefined) {
  //     const stateMoal = TaskIdsModal.getStateModal4Task(satgeData.task, modelValue.value.type);
  //     // console.log('toDealRow list',list)
  //     // console.log('formValue data',data)
  //     if (stateMoal !== undefined) {
  //       if (toADDFlag.value) {
  //         const list = StateMoal.getStateId(stateMoal, tosave.state);
  //         // console.log(list,tosave.id,stateMoal)
  //         if (tosave.id !== undefined) {
  //           list.push(tosave.id);
  //           taskList.addTaskData(
  //               new TaskData(
  //                   tosave.id,
  //                   tosave.name,
  //                   modelValue.value.type,
  //                   showStage,
  //                   tosave.desc,
  //                   tosave.timeMentionModal,
  //               ),
  //           );
  //           surfaceSetting.maxId++;
  //         }
  //       } else {
  //         const data = taskList.getTaskDataById(tosave.id);
  //         // console.log("addNew task", tosave, data);
  //         if (data !== undefined) {
  //           data.name = tosave.name;
  //           data.mentionTime = TimeMentionModal.computeMentionTime(tosave.timeMentionModal);
  //           data.desc = tosave.desc;
  //           data.timeMentionModal = tosave.timeMentionModal;
  //           data.type = modelValue.value.type;
  //           if (tosave.id !== undefined) {
  //             // console.log("addNew task", tosave.state, getState());
  //             const state = getState();
  //             if (tosave.state !== state) {
  //               StateMoal.changeIdState(stateMoal, tosave.id, state, tosave.state);
  //             }
  //           }
  //           // console.log('addNew task',stateMoal,tosave.id,surfaceSetting.getTaskState(modelValue.value.type),tosave.state);
  //         }
  //       }
  //     }
  //   } else message.error("阶段不存在或已删除");
  // }
  modelValue.value.show = false;
};
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      // message.success("Valid");
      // console.log({...formValue.value, ...formValue.value.timeMentionModal})
      formValue.value.mentionTime = TimeMentionModal.computeMentionTime(formValue.value.timeMentionModal, formValue.value.type)
      addItem({ ...formValue.value, ...formValue.value.timeMentionModal });
      console.log({ ...formValue.value, ...formValue.value.timeMentionModal })
    } else {
      // console.log(errors);
      //  message.error(errors);
    }
  });

};
</script>

<style scoped>
</style>
